﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Blog_BLL
{
    /// <summary>
    /// 请求响应Json数据
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// 响应Json数据
        /// </summary>
        /// <param name="_StateCode">响应状态码</param>
        /// <param name="_Messages">响应提示消息</param>
        /// <param name="_JsonData">响应json数据</param>
        /// <returns></returns>
        public static string ResponseData(StateCode _StateCode, string _Messages, Object _JsonData)
        {
            JsonMessages jMessages = new JsonMessages
            {
                StateCode = _StateCode,
                Messages = _Messages,
                JsonData = _JsonData
            };
            return JsonConvert.SerializeObject(jMessages);
        }
        /// <summary>
        /// 自定义格式响应Json数据
        /// </summary>
        /// <param name="_JsonData"></param>
        /// <returns></returns>
        public static string ToJsonData(string _JsonData)
        {
            return _JsonData;
        }
        /// <summary>
        /// 任意类型转换Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string ToJsonData<T>(T t)
        {
            return JsonConvert.SerializeObject(t, Formatting.Indented, new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
        }
        /// <summary>
        /// json格式转换对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T ToJsonObject<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }
    }
    /// <summary>
    /// 返回json格式对象
    /// </summary>
    [Serializable]
    public class JsonMessages
    {
        private Object jsonData;
        /// <summary>
        /// 响应状态
        /// </summary>
        public StateCode StateCode { set; get; }
        /// <summary>
        /// 响应提示消息
        /// </summary>
        public string Messages { set; get; }
        /// <summary>
        /// 响应json数据
        /// </summary>
        public Object JsonData
        {
            set { jsonData = value; }
            get
            {
                if (jsonData == null)
                    return "[]";
                else
                    return jsonData;

            }
        }
    }
    /// <summary>
    /// 响应状态码
    /// </summary>
    public enum StateCode
    {
        /// <summary>
        /// 成功状态码
        /// </summary>
        success = 200,
        /// <summary>
        /// 失败状态码
        /// </summary>
        failure = 500,
    }
}
